package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.leyou.common.advice.exception.LyException;
import com.leyou.common.vo.PageResult;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDeatailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.mapper.StockMapper;
import com.leyou.item.pojo.*;
import enums.ExceptionEnum;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {

    @Autowired
    SpuMapper spuMapper;
    @Autowired
    SpuDeatailMapper spuDeatailMapper;
    @Autowired
    CategoryService categoryService;
    @Autowired
    BrandService brandService;
    @Autowired
    SkuMapper skuMapper;
    @Autowired
    StockMapper stockMapper;



    public PageResult<Spu> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {

        //分页：
        PageHelper.startPage(page,rows);
        //过滤：
        Example example = new Example(Spu.class);
        Example.Criteria criteria =example.createCriteria();

        //搜索字段：
        if (StringUtil.isNotEmpty(key)){
            criteria.andLike("title","%"+key+"%");
        }
        //上下架过滤：
        if (saleable != null){
            criteria.andEqualTo("saleable",saleable);
        }
        //默认排序
        example.setOrderByClause("last_update_time DESC");
        List<Spu> list = spuMapper.selectByExample(example);

        //解析品牌名称：
        loadCategoryAndBrandName(list);
        //判断：
        if (CollectionUtils.isEmpty(list)){
            throw  new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        //解析分页的结果.
        PageInfo<Spu> pageInfo =  new PageInfo<>(list);
        return new PageResult<>(pageInfo.getTotal(),list);
    }

    private void loadCategoryAndBrandName(List<Spu> list) {
        for (Spu spu:list){
         List<String> names =  categoryService.queryByIds(Arrays.asList(spu.getCid1(),spu.getCid2(),spu.getCid3())).stream().map(Category::getName).collect(Collectors.toList());
         //处理分类名称：
            spu.setCname(StringUtils.join(names, '/'));

          //处理分类名称：
            spu.setBname(brandService.queryById(spu.getBrandId()).getName());

        }
    }


   @Transactional
    public void saveGoods(Spu spu) {

        //新增spu
        spu.setId(null);
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(new Date());
        spu.setSaleable(true);
        spu.setValid(false);
        int count = spuMapper.insert(spu);
        if (count !=1){

            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        //新增detail;
        SpuDetail detail = spu.getSpuDetail();
        detail.setSpuId(spu.getId());
        spuDeatailMapper.insert(detail);

        //批量新增库存的集合：
        List<Stock> stockList = new ArrayList<Stock>();
        //新增sku
        List<Sku> skus = spu.getSkus();
        for (Sku sku:skus){
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(new Date());
            sku.setSpuId(spu.getId());
           count= skuMapper.insert(sku);
           if (count !=1){
               throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
           }
            //新增库存：
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            stockList.add(stock);
        }
        //批量新增：
        stockMapper.insertList(stockList);
    }

    /***
     * 根据spuId查询spu详情
     * @param spuId
     * @return
     */

    public SpuDetail queryDetailById(Long spuId) {
        SpuDetail spuDetail  = new SpuDetail();
        spuDetail.setSpuId(spuId);
        spuDeatailMapper.select(spuDetail);
        if (spuDetail == null){
            throw new LyException(ExceptionEnum.GOODS_DETAIL_NOT_FOUND);
        }

        return spuDetail;
    }

    public List<Sku> querySkuBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
      List<Sku> list =  skuMapper.select(sku);
      if (CollectionUtils.isEmpty(list)){
          throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
      }
      return list;

    }
}
